package org.esk.dablog.web.forms;

import org.esk.dablog.model.Comment;
import org.esk.dablog.model.Entry;
import org.esk.dablog.model.Author;
import org.esk.dablog.service.EntryManager;
import org.esk.dablog.service.UserManager;
import org.esk.dablog.web.util.RequestUtils;
import org.esk.dablog.web.functions.EntryFunctions;
import org.esk.dablog.exceptions.ParameterException;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.acegisecurity.annotation.Secured;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * This class 
 * User: esk
 * Date: Dec 12, 2006
 * Time: 6:22:46 PM
 * $Id:$
 */
@Secured({"ROLE_REGISTERED_USER"})
public abstract class AbstractAddComment extends SimpleFormController {
    private EntryManager entryManager;
    private UserManager userManager;
    private boolean safeInput = true;


    protected AbstractAddComment() {
        setCommandClass(Comment.class);
    }

    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
        Author a = userManager.getAuthorByUsername(request.getRemoteUser());
        Comment c = (Comment) command;
        c.setAuthor(a);
        c.setDate(new Date());
        c.setIp(request.getRemoteAddr());
        if(safeInput) {
            c.setText(EntryFunctions.toBr(c.getText()));
        }
        processComment(request, c);
        saveComment(c);
        return new ModelAndView(new RedirectView(getSuccessView(), true));
    }

    /**
     * processes comment in derived class
     * @param request
     * @param c
     */
    protected void processComment(HttpServletRequest request, Comment c) throws Exception {

    }

    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        long entryId = RequestUtils.extractLongParameter(request);
        Entry e = getEntryManager().getEntry(Entry.class, entryId);
        Comment c = (Comment) getCommandClass().newInstance();
        c.setEntry(e);
        return c;
    }



    /**            1
     * saves comment. overrideable in descendants
     * @param c
     */
    protected void saveComment(Comment c) {
        entryManager.saveComment(c);
    }

    public EntryManager getEntryManager() {
        return entryManager;
    }

    public void setEntryManager(EntryManager entryManager) {
        this.entryManager = entryManager;
    }

    public UserManager getUserManager() {
        return userManager;
    }

    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }


    public void setSafeInput(boolean safeInput) {
        this.safeInput = safeInput;
    }
}
